package com.jingbian.cppccbackend.controller.admin;

import com.jingbian.cppccbackend.entity.Admins;
import com.jingbian.cppccbackend.entity.Result;

import com.jingbian.cppccbackend.entity.Users;
import com.jingbian.cppccbackend.service.admin.AdminsService;
import com.jingbian.cppccbackend.utils.JwtUtil;
import com.jingbian.cppccbackend.utils.ResultUtil;
import com.jingbian.cppccbackend.utils.ThreadLocalUtil;
import com.jingbian.cppccbackend.entity.vo.AdminLoginVO;
import com.jingbian.cppccbackend.entity.vo.PageVO;
import jakarta.validation.constraints.Pattern;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 管理员信息表 前端控制器
 * </p>
 *
 * @author yezi
 * @since 2025-02-09
 */
@Slf4j
@RestController
@Validated
@RequestMapping("/admins")
public class AdminsController {
    @Autowired
    private AdminsService adminsService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @PostMapping("/login")
    public Result<AdminLoginVO> login(@Pattern(regexp="^\\S{5,16}$")String account,
                                    @Pattern(regexp="^\\S{5,16}$")String password) {
        //根据账号查找管理员
        Admins admin = adminsService.findByAccount(account);
        //判断账号是否存在
        if (admin == null) {
            return ResultUtil.fail("用户名错误");
        }
        //判断密码是否正确
        if (admin.getPassword().equals(password)) {
            Map<String, Object> claims = new HashMap<>();
            claims.put("aid", admin.getAid());
            claims.put("account", admin.getAccount());
            claims.put("isSuperAdmin", admin.getIsSuperAdmin());
            // 明确设置管理员token过期时间为1小时
            String token = JwtUtil.genToken(claims);
            // 根据是否为超级管理员设置角色标识
            Integer role = admin.getIsSuperAdmin() ? 1 : 0;
            AdminLoginVO loginVO = new AdminLoginVO(token, role);
            //把token存储到redis中
            ValueOperations<String, String> Operations = stringRedisTemplate.opsForValue();
            Operations.set(token, token, 1, TimeUnit.HOURS); // 明确设置1小时过期
            return ResultUtil.success(loginVO);
        }
        return ResultUtil.fail("密码错误");
    }
    //查看管理员个人信息
    @GetMapping("/getAdminInfo")
    public Result<Admins> getAdminInfo() {
        Map<String, Object> map = ThreadLocalUtil.get();
        String account=(String)map.get("account");
        Admins admin = adminsService.findByAccount(account);
        if (admin != null) {
            return ResultUtil.success(admin);
        }
        return ResultUtil.fail("用户不存在");
    }

    @GetMapping("/getUsers")
    public Result<PageVO<Users>> getUsers(
            Integer pageNum,
            Integer pageSize,
            @RequestParam(required = false) String searchText,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate,
            @RequestParam(required = false,defaultValue = "asc") String sortType,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String identity,
            @RequestParam(required = false) String region,
            @RequestParam(required = false) String affiliation,
            @RequestParam(required = false) String ethnicity,
            @RequestParam(required = false) String gender,
            @RequestParam(required = false) Boolean onlyApproved
    ) {
        System.out.println("hahh"+onlyApproved);
        String auditStatus = onlyApproved != null && onlyApproved ? "已通过" : null;
        PageVO<Users> users = adminsService.getUsers(pageNum, pageSize, searchText, startDate, endDate,
                sortType, status, identity, region, affiliation, ethnicity, gender, auditStatus);
        return ResultUtil.success(users);
    }

    @GetMapping("/getUserDetail/{uid}")
    public Result<Users> getUsersDetails(@PathVariable Integer uid){
        return ResultUtil.success(adminsService.getUsersDetails(uid));
    }

    //审核
    @PutMapping("/updateUserStatus/{uid}")
    public Result<String> updateStatus(
            @PathVariable Integer uid,
            @RequestParam String status
    ) {
        adminsService.updateStatus(uid, status);
        return ResultUtil.success("状态更新成功");
    }

    //修改用户
    @PutMapping("/updateUser")
    public Result<String> updateUser(@RequestBody Users user) {
        if (adminsService.updateUser(user)) {
            return ResultUtil.success("修改成功");
        }
        return ResultUtil.fail("修改失败");
    }
    
    //删除用户
    @DeleteMapping("/deleteUser/{uid}")
    public Result<String> deleteUser(@PathVariable Integer uid) {
        if (adminsService.deleteUser(uid)) {
            return ResultUtil.success("删除成功");
        }
        return ResultUtil.fail("删除失败");
    }

    //重置用户密码
    @PutMapping("/resetPassword/{uid}")
    public Result<String> resetPassword(
            @PathVariable Integer uid,
            @Pattern(regexp = "^\\S{6,16}$") @RequestParam String newPassword
    ) {
        if (adminsService.resetPassword(uid, newPassword)) {
            return ResultUtil.success("密码重置成功");
        }
        return ResultUtil.fail("密码重置失败");
    }

    @GetMapping("/exportUsers")
    public ResponseEntity<byte[]> exportUsers(
            @RequestParam(required = false) String searchText,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate,
            @RequestParam(required = false,defaultValue = "asc") String sortType,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String identity,
            @RequestParam(required = false) String region,
            @RequestParam(required = false) String affiliation,
            @RequestParam(required = false) String ethnicity,
            @RequestParam(required = false) String gender,
            @RequestParam(required = false) Boolean onlyApproved
    ) throws IOException {
        log.info("开始导出用户列表Excel，参数：searchText={}, startDate={}, endDate={}, sortType={}, status={}, identity={}, region={}, affiliation={}, ethnicity={}, gender={}, onlyApproved={}",
                searchText, startDate, endDate, sortType, status, identity, region, affiliation, ethnicity, gender, onlyApproved);

        try {
            // 获取用户列表数据
            String auditStatus = onlyApproved != null && onlyApproved ? "已通过" : null;
            List<Users> usersList = adminsService.getUsersForExport(searchText, startDate, endDate, sortType,
                    status, identity, region, affiliation, ethnicity, gender, auditStatus);
            log.info("获取到 {} 条数据", usersList.size());

            // 创建工作簿
            try (XSSFWorkbook workbook = new XSSFWorkbook()) {
                Sheet sheet = workbook.createSheet("用户列表");

                // 设置表头样式
                CellStyle headerStyle = workbook.createCellStyle();
                headerStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
                headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
                Font headerFont = workbook.createFont();
                headerFont.setBold(true);
                headerStyle.setFont(headerFont);

                // 创建表头
                Row headerRow = sheet.createRow(0);
                String[] header = {"用户ID", "姓名", "手机号", "性别", "民族", "出生日期", "单位", "身份", "界别", "地区", "状态", "注册时间", "考核分数"};

                for (int i = 0; i < header.length; i++) {
                    Cell cell = headerRow.createCell(i);
                    cell.setCellValue(header[i]);
                    cell.setCellStyle(headerStyle);
                    sheet.autoSizeColumn(i);
                }

                // 填充数据
                int rowNum = 1;
                for (Users user : usersList) {
                    Row row = sheet.createRow(rowNum++);
                    row.createCell(0).setCellValue(user.getUid());
                    row.createCell(1).setCellValue(user.getUname());
                    row.createCell(2).setCellValue(user.getPhone());
                    row.createCell(3).setCellValue(user.getGender());
                    row.createCell(4).setCellValue(user.getEthnicity());
                    
                    // 设置出生日期
                    Cell birthDateCell = row.createCell(5);
                    if (user.getBirthDate() != null) {
                        birthDateCell.setCellValue(user.getBirthDate());
                        CellStyle dateStyle = workbook.createCellStyle();
                        dateStyle.setDataFormat(workbook.createDataFormat().getFormat("yyyy-mm-dd"));
                        birthDateCell.setCellStyle(dateStyle);
                    }

                    row.createCell(6).setCellValue(user.getUnit());
                    row.createCell(7).setCellValue(user.getIdentity());
                    row.createCell(8).setCellValue(user.getAffiliation());
                    row.createCell(9).setCellValue(user.getRegion());

                    row.createCell(10).setCellValue(user.getStatus());

                    // 设置注册时间
                    Cell registrationTimeCell = row.createCell(11);
                    if (user.getRegistrationTime() != null) {
                        registrationTimeCell.setCellValue(user.getRegistrationTime());
                        CellStyle dateStyle = workbook.createCellStyle();
                        dateStyle.setDataFormat(workbook.createDataFormat().getFormat("yyyy-mm-dd hh:mm:ss"));
                        registrationTimeCell.setCellStyle(dateStyle);
                    }

                    // 设置分数，新增的列
                    Cell scoreCell = row.createCell(12);
                    if (user.getScore() != null) {
                        scoreCell.setCellValue(user.getScore());
                        // 设置数字格式为一位小数
                        CellStyle scoreStyle = workbook.createCellStyle();
                        scoreStyle.setDataFormat(workbook.createDataFormat().getFormat("0.0"));
                        scoreCell.setCellStyle(scoreStyle);
                    } else {
                        scoreCell.setCellValue(0.0);
                    }
                }

                // 写入字节数组
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                workbook.write(outputStream);
                byte[] content = outputStream.toByteArray();

                // 设置响应头
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
                String filename = URLEncoder.encode("用户列表.xlsx", StandardCharsets.UTF_8).replaceAll("\\+", "%20");
                headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename*=UTF-8''" + filename);

                log.info("Excel文件生成成功，大小: {} bytes", content.length);
                return new ResponseEntity<>(content, headers, HttpStatus.OK);
            }
        } catch (Exception e) {
            log.error("导出Excel失败", e);
            throw new RuntimeException("导出Excel失败: " + e.getMessage());
        }
    }

    // 获取用户统计数据
    @GetMapping("/statistics")
    public Result<Map<String, Object>> getUserStatistics() {
        return ResultUtil.success(adminsService.getUserStatistics());
    }

    // 获取待审核用户数量
    @GetMapping("/pendingAuditCount")
    public Result<Integer> getPendingAuditCount() {
        return ResultUtil.success(adminsService.getPendingAuditCount());
    }

    // 获取用户界别分布
    @GetMapping("/affiliationDistribution")
    public Result<List<Map<String, Object>>> getUserAffiliationDistribution() {
        return ResultUtil.success(adminsService.getUserAffiliationDistribution());
    }

    // 获取用户注册趋势 - 修改为支持日期范围
    @GetMapping("/registrationTrend")
    public Result<List<Map<String, Object>>> getUserRegistrationTrend(
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate) {
        return ResultUtil.success(adminsService.getUserRegistrationTrend(startDate, endDate));
    }

    // 导出用户变化趋势数据
    @GetMapping("/exportTrendData")
    public ResponseEntity<byte[]> exportTrendData(
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate
    ) throws IOException {
        log.info("开始导出用户变化趋势数据，参数：startDate={}, endDate={}", startDate, endDate);

        try {
            // 获取用户趋势数据
            List<Map<String, Object>> trendData = adminsService.getUserRegistrationTrend(startDate, endDate);
            log.info("获取到 {} 条趋势数据", trendData.size());

            // 创建工作簿
            try (XSSFWorkbook workbook = new XSSFWorkbook()) {
                Sheet sheet = workbook.createSheet("用户变化趋势");

                // 设置表头样式
                CellStyle headerStyle = workbook.createCellStyle();
                headerStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
                headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
                Font headerFont = workbook.createFont();
                headerFont.setBold(true);
                headerStyle.setFont(headerFont);

                // 创建表头
                Row headerRow = sheet.createRow(0);
                String[] header = {"日期", "新增用户数量"};

                for (int i = 0; i < header.length; i++) {
                    Cell cell = headerRow.createCell(i);
                    cell.setCellValue(header[i]);
                    cell.setCellStyle(headerStyle);
                    sheet.autoSizeColumn(i);
                }

                // 填充数据
                int rowNum = 1;
                for (Map<String, Object> data : trendData) {
                    Row row = sheet.createRow(rowNum++);
                    row.createCell(0).setCellValue(data.get("date").toString());
                    row.createCell(1).setCellValue(Integer.parseInt(data.get("value").toString()));
                }

                // 写入字节数组
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                workbook.write(outputStream);
                byte[] content = outputStream.toByteArray();

                // 设置响应头
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
                String filename = URLEncoder.encode("用户变化趋势数据.xlsx", StandardCharsets.UTF_8).replaceAll("\\+", "%20");
                headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename*=UTF-8''" + filename);

                log.info("Excel文件生成成功，大小: {} bytes", content.length);
                return new ResponseEntity<>(content, headers, HttpStatus.OK);
            }
        } catch (Exception e) {
            log.error("导出Excel失败", e);
            throw new RuntimeException("导出Excel失败: " + e.getMessage());
        }
    }

    //根据部门id获取部门名称
    @GetMapping("/getDepartmentName/{departmentId}")
    public Result<String> getDepartmentName(@PathVariable String departmentId) {
        if (departmentId == null || departmentId.trim().isEmpty()) {
            return ResultUtil.fail("部门ID不能为空");
        }
        String departmentName = adminsService.getDepartmentName(departmentId);
        if (departmentName == null) {
            return ResultUtil.fail("未找到对应的部门");
        }
        return ResultUtil.success(departmentName);
    }

    //根据部门id获取社情民意部门名称
    @GetMapping("/getDepartmentName2/{departmentId}")
    public Result<String> getDepartmentName2(@PathVariable String departmentId) {
        if (departmentId == null || departmentId.trim().isEmpty()) {
            return ResultUtil.fail("部门ID不能为空");
        }
        String departmentName = adminsService.getDepartmentName2(departmentId);
        if (departmentName == null) {
            return ResultUtil.fail("未找到对应的部门");
        }
        return ResultUtil.success(departmentName);
    }

    // 保存用户分数
    @PutMapping("/updateUserScore/{uid}")
    public Result<String> updateUserScore(
            @PathVariable Integer uid,
            @RequestParam Double score
    ) {
        if (score < 0 || score > 100) {
            return ResultUtil.fail("分数必须在0-100之间");
        }
        if (adminsService.updateUserScore(uid, score)) {
            return ResultUtil.success("分数更新成功");
        }
        return ResultUtil.fail("分数更新失败");
    }

    // 清零所有用户分数
    @PutMapping("/clearAllScores")
    public Result<String> clearAllScores() {
        if (adminsService.clearAllScores()) {
            return ResultUtil.success("所有分数已清零");
        }
        return ResultUtil.fail("清零操作失败");
    }
}



